package com.ailanyin.security.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/26 0026 下午 17:32
 */
@Service
public class SecurityUserService {

    /**
     * 存放登录用户的 UserDetails, 用作缓存
     */
    private final Map<String, UserDetails> userDetailsMap = new ConcurrentHashMap<>(128);

    /**
     * 添加登录用户的 UserDetails
     *
     * @param username    key
     * @param userDetails value
     */
    public void addUserDetailsToMap(String username, UserDetails userDetails) {
        userDetailsMap.put(username, userDetails);
    }

    /**
     * 删除登录用户的 UserDetails
     *
     * @param username key
     */
    public void delUserDetailsFromMap(String username) {
        userDetailsMap.remove(username);
        SecurityContextHolder.clearContext();
    }

    /**
     * 获取登录用户的 UserDetails
     *
     * @param username key
     * @return UserDetails
     */
    public UserDetails getUserDetailsFromMap(String username) {
        return userDetailsMap.get(username);
    }

    /**
     * 每天凌晨 1点钟 清空 map
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void clearUserDetailsMap() {
        userDetailsMap.clear();
    }
}
